<?php
class ManageBannersController extends Controller {

	//public $backend_left_menu = "_left_menu";
	public $backend_left_menu = "application.modules.banners.views.admin_menu._left_menu";
	public $backend_left_menu_datas = array('list'	=>	array());
	//public $backend_left_menu_datas = false;
	private $_model;
	public $layout='//layouts/main';
	public $pageTitle="Manage products";

	/*
	public function allowedActions() {
			return '';
	}
	
	/*
	public function accessRules() {
			return array(
					array('deny',
							'actions'=>array('delete', 'create', 'update'),
							'users'=>array('?'),
					),
					array('deny',
							'actions'=>array('delete', 'create', 'update'),
							'users'=>array('guest'),
					),
					array('allow',
							'actions'=>array('admin'),
							'roles'=>array('guest'),
					),
					array('allow',
							'actions'=>array('delete', 'create', 'update'),
							'roles'=>array('superuser'),
					),
			);
			//return '';
	}
	*/
	public function init()
	{
			Yii::app()->theme = 'backend';
			parent::init();
	}

	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id, 'Banner'),
		));
	}

	public function actionCreate() {
		$this->pageTitle = "Add new banner"; 
		$model = new Banner;

		//$this->performAjaxValidation($model, 'static-page-form');

		if (isset($_POST['Banner'])) {
			$model->setAttributes($_POST['Banner']);
			$fileUpload = CUploadedFile::getInstance($model, 'image');
			if (isset($fileUpload)) {
				list($width, $height, $type, $attr) = getimagesize($fileUpload->getTempName());
				if($width != $this->module->image['width'] 
						|| $height != $this->module->image['height']){
					$model->addError('image', 'Hình ảnh phải đúng kích thước '
							.$this->module->image['width']
							.'x'.$this->module->image['height'].' pixel.');
				}else{
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url']; 
					if (!is_dir($uploadPath))
						mkdir($uploadPath,0777,true);
					
					$filename = time(). $fileUpload->getName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
					$fileUpload->saveAs($uploadPath . $filename);
					//CVarDumper::dump($uploadPath . $filename, 3, true);	exit;

					//Create lager and thumbnail image
					Yii::import('ext.phpthumb.EasyPhpThumb');
					$thumbsPath = $uploadPath;

					// thumbnails image
					$thumbs = new EasyPhpThumb();
					$thumbs->init();
					$thumbs->setThumbsDirectory($thumbsPath);
					$thumbs->load($uploadPath . $filename)
							->resize(Yii::app()->controller->module->image['thumbnail']['width'], 
											 Yii::app()->controller->module->image['thumbnail']['height']
											)
							->save('thumb_'.$filename);
					
					$model->image = $filename;
					
					if ($model->save()) {
						if (Yii::app()->getRequest()->getIsAjaxRequest())
							Yii::app()->end();
						else
							$this->redirect(array('view', 'id' => $model->id));
					}
				}
			}else{
				$model->addError('image', 'Chưa chọn hình ảnh banner.');
			}
		}
		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		$this->pageTitle = "Update new banner"; 
		$model = $this->loadModel($id, 'Banner');
		
		//$this->performAjaxValidation($model, 'static-page-form');
		
		if (isset($_POST['Banner'])) {
			$model->setAttributes($_POST['Banner']);
			$fileUpload = CUploadedFile::getInstance($model, 'image');
			if (isset($fileUpload)) {
				list($width, $height, $type, $attr) = getimagesize($fileUpload->getTempName());
				if($width != $this->module->image['width']
						|| $height != $this->module->image['height']){
					$model->addError('image', 'Hình ảnh phải đúng kích thước '
							.$this->module->image['width']
							.'x'.$this->module->image['height'].' pixel.');
				}else{
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url'];
					if (!is_dir($uploadPath))
						mkdir($uploadPath,0777,true);
						
					$filename = time(). $fileUpload->getName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
					$fileUpload->saveAs($uploadPath . $filename);
					//CVarDumper::dump($uploadPath . $filename, 3, true);	exit;
		
					//Create lager and thumbnail image
					Yii::import('ext.phpthumb.EasyPhpThumb');
					$thumbsPath = $uploadPath;
		
					// thumbnails image
					$thumbs = new EasyPhpThumb();
					$thumbs->init();
					$thumbs->setThumbsDirectory($thumbsPath);
					$thumbs->load($uploadPath . $filename)
					->resize(Yii::app()->controller->module->image['thumbnail']['width'],
							Yii::app()->controller->module->image['thumbnail']['height']
					)
					->save('thumb_'.$filename);
					
					try{
						if(is_file($uploadPath.'/'.$model->image)){
							unlink($uploadPath.'/'.$model->image);
						}
						if(is_file($uploadPath.'/thumb_'.$model->image)){
							unlink($uploadPath.'/thumb_'.$model->image);
						}
					}catch (Exception $err){}
					
					$model->image = $filename;
						
					if ($model->save()) {
						if (Yii::app()->getRequest()->getIsAjaxRequest())
							Yii::app()->end();
						else
							$this->redirect(array('view', 'id' => $model->id));
					}
				}
			}else{
				$model->addError('image', 'Chưa chọn hình ảnh banner.');
			}
		}
		$this->render('create', array( 'model' => $model));
	}

	public function actionDelete($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			//$this->loadModel($id, 'Banner')->delete();
			$model = $this->loadModel($id);
			
			$img = $model->image;
			// X�a khoi db
			if ($model->delete()) 
			{
				// X�a image
				$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url'];
				try{
					if(is_file($uploadPath.'/'.$img)){
						unlink($uploadPath.'/'.$img);
					}
					if(is_file($uploadPath.'/thumb_'.$img)){
						unlink($uploadPath.'/thumb_'.$img);
					}
				}catch (Exception $err){}
			}
			
			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('admin'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}

	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Banner');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		if (isset($_POST['banner-pages-grid_c0'])) {
			foreach ($_POST['banner-pages-grid_c0'] as $ID)
			{
				$model = $this->loadModelByID($ID);

				// Xoa khoi db
				if ($model->delete() == 'ALL')
				{
					// Xoa image
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url'];
					$filename = $uploadPath . $model->image;
					if (is_file($filename)) @unlink($filename);
					$filenameThumb = $uploadPath . 'thumb_' . $model->image;
					if (is_file($filenameThumb)) @unlink($filenameThumb);
					$filenameLager = $uploadPath . 'lager_' . $model->image;
					if (is_file($filenameLager)) @unlink($filenameLager);
				}
			}
		}
		$model = new Banner('search');
		$model->unsetAttributes();
		if (isset($_GET['Banner'])) {
			$model->setAttributes($_GET['Banner']);
		}
		$this->render('admin', array(
			'model' => $model,
		));
	}
	
	protected function performAjaxValidation($models)
	{
			if(isset($_POST['ajax']) && $_POST['ajax']==='static-page-form')
			{
					echo CActiveForm::validate($models);
					Yii::app()->end();
			}
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=Banner::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
	
	public function loadModelByID($id)
	{
			$model = Banner::model()->findByPk($id);
			if ($model === null)
					throw new CHttpException(404, 'The requested page does not exist.');
			return $model;
	}
}